package com.zhq.blog.core.domain.admin;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Transient;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.repository.JpaRepository;







import com.zhq.blog.core.domain.BasePersistentDomain;


@Entity
public class Operator extends BasePersistentDomain<OperatorRepository>{
	
	@Transient private Role role;
	private String password;
	private String name;
	private String ip;
	private String loginTime;
	
	public Operator(){}
	
	



	public Operator(String name,String password,String selectRecommends, String userRecommends,
			String gameRecommends, String safeRecommends, String moneyRecommends) {
		super();
		this.password = password;
		this.name = name;
		this.selectRecommends = selectRecommends;
		this.userRecommends = userRecommends;
		this.gameRecommends = gameRecommends;
		this.safeRecommends = safeRecommends;
		this.moneyRecommends = moneyRecommends;
	}
	
	





	public Operator( String name, String password, String ip,
			String loginTime, String selectRecommends, String userRecommends,
			String gameRecommends, String safeRecommends, String moneyRecommends) {
		super();
		this.password = password;
		this.name = name;
		this.ip = ip;
		this.loginTime = loginTime;
		this.selectRecommends = selectRecommends;
		this.userRecommends = userRecommends;
		this.gameRecommends = gameRecommends;
		this.safeRecommends = safeRecommends;
		this.moneyRecommends = moneyRecommends;
	}





	public Operator(String password, String name) {
		super();
		this.password = password;
		this.name = name;
	}
	
	public void logon(){
		
	}
	public void checkPermission(AdminControllerDescription action){
		
	}
	
	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}
	
	





	public String getLoginTime() {
		return loginTime;
	}





	public void setLoginTime(String loginTime) {
		this.loginTime = loginTime;
	}





	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public List<SelectRecommend> getSelectRecommendList() {
		return selectRecommendList;
	}

	public void setSelectRecommendList(List<SelectRecommend> selectRecommendList) {
		this.selectRecommendList = selectRecommendList;
	}

	public String getSelectRecommends() {
		return selectRecommends;
	}

	public void setSelectRecommends(String selectRecommends) {
		this.selectRecommends = selectRecommends;
	}

	//权限控制
	
	public List<UserRecommend> getUserRecommendList() {
		return userRecommendList;
	}

	public void setUserRecommendList(List<UserRecommend> userRecommendList) {
		this.userRecommendList = userRecommendList;
	}

	public String getUserRecommends() {
		return userRecommends;
	}

	public void setUserRecommends(String userRecommends) {
		this.userRecommends = userRecommends;
	}

	public List<GameRecommend> getGameRecommendList() {
		return gameRecommendList;
	}

	public void setGameRecommendList(List<GameRecommend> gameRecommendList) {
		this.gameRecommendList = gameRecommendList;
	}

	public String getGameRecommends() {
		return gameRecommends;
	}

	public void setGameRecommends(String gameRecommends) {
		this.gameRecommends = gameRecommends;
	}

	public List<SafeRecommend> getSafeRecommendList() {
		return safeRecommendList;
	}

	public void setSafeRecommendList(List<SafeRecommend> safeRecommendList) {
		this.safeRecommendList = safeRecommendList;
	}

	public String getSafeRecommends() {
		return safeRecommends;
	}

	public void setSafeRecommends(String safeRecommends) {
		this.safeRecommends = safeRecommends;
	}

	public List<MoneyRecommend> getMoneyRecommendList() {
		return moneyRecommendList;
	}

	public void setMoneyRecommendList(List<MoneyRecommend> moneyRecommendList) {
		this.moneyRecommendList = moneyRecommendList;
	}

	public String getMoneyRecommends() {
		return moneyRecommends;
	}

	public void setMoneyRecommends(String moneyRecommends) {
		this.moneyRecommends = moneyRecommends;
	}

	public Operator save(Operator operator) {
        fromViewToDateBase(operator);
        return context.getOperatorRepository().save(operator);

    }

    public Operator findOne(Long id) {
    	Operator operator = context.getOperatorRepository().findOne(id);
        fromDateBaseToView(operator);
        return operator;
    }
	
	/**
     * 数据库到视图的字段转化
     * 
     */
    public void fromDateBaseToView(Operator operator) {
    	operator.setSelectRecommendList(getSelectRecommendFromString(operator.getSelectRecommends()));
    	operator.setUserRecommendList(getUserRecommendFromString(operator.getUserRecommends()));
    	operator.setGameRecommendList(getGameRecommendFromString(operator.getGameRecommends()));
    	operator.setSafeRecommendList(getSafeRecommendFromString(operator.getSafeRecommends()));
    	operator.setMoneyRecommendList(getMoneyRecommendFromString(operator.getMoneyRecommends()));
    }
    
    /**
     * 视图到数据库的字段转化
     * 
     */
    public void fromViewToDateBase(Operator operator) {
    	operator.setSelectRecommends(getStringFromSelectList(operator.getSelectRecommendList()));
    	operator.setUserRecommends(getStringFromUserSelectList(operator.getUserRecommendList()));
    	operator.setGameRecommends(getStringFromGameselectList(operator.getGameRecommendList()));
    	operator.setSafeRecommends(getStringFromSafeselectList(operator.getSafeRecommendList()));
    	operator.setMoneyRecommends(getStringFromMoneyselectList(operator.getMoneyRecommendList()));
    }
	
	@Transient
    private List<SelectRecommend> selectRecommendList;
 
    private String selectRecommends;
    
    @Transient
    private List<UserRecommend> userRecommendList;
 
    private String userRecommends;
    
    @Transient
    private List<GameRecommend> gameRecommendList;
 
    private String gameRecommends;
    
    @Transient
    private List<SafeRecommend> safeRecommendList;
 
    private String safeRecommends;
    
    @Transient
    private List<MoneyRecommend> moneyRecommendList;
 
    private String moneyRecommends;
	
    //游戏管理
    public enum GameRecommend {
		LUCY("幸运28"),HAPPY("欢乐11"),PK("PK10");	
		public String description;

		GameRecommend(final String description) {
			this.description = description;
		}
		
        public static GameRecommend valueOf(int ordinal) {
            if (ordinal < 0 || ordinal >= values().length) {
                throw new IndexOutOfBoundsException("Invalid ordinal");
            }
            return values()[ordinal];
        }
	}
	
	//枚举商品模块。
	public enum SelectRecommend {
		PRIZE("奖品管理"),EXPIRY("兑奖管理");	
		public String description;

		SelectRecommend(final String description) {
			this.description = description;
		}
		
        public static SelectRecommend valueOf(int ordinal) {
            if (ordinal < 0 || ordinal >= values().length) {
                throw new IndexOutOfBoundsException("Invalid ordinal");
            }
            return values()[ordinal];
        }
	}
	//用户模块。
	public enum UserRecommend {
		USER("用户管理"),SALE("活动管理");	
		public String description;

		UserRecommend(final String description) {
			this.description = description;
		}
		
        public static UserRecommend valueOf(int ordinal) {
            if (ordinal < 0 || ordinal >= values().length) {
                throw new IndexOutOfBoundsException("Invalid ordinal");
            }
            return values()[ordinal];
        }
	}
	
	//用户模块。
		public enum SafeRecommend {
			OPERATOR("管理员管理"),RECORD("操作日志管理");	
			public String description;

			SafeRecommend(final String description) {
				this.description = description;
			}
			
	        public static SafeRecommend valueOf(int ordinal) {
	            if (ordinal < 0 || ordinal >= values().length) {
	                throw new IndexOutOfBoundsException("Invalid ordinal");
	            }
	            return values()[ordinal];
	        }
		}
	
	//用户模块。
		public enum MoneyRecommend {
			BUSINESSMAN	("商户管理"),CARD("充值卡管理"),Record("支付记录");	
			public String description;

			MoneyRecommend(final String description) {
				this.description = description;
			}
			
	        public static MoneyRecommend valueOf(int ordinal) {
	            if (ordinal < 0 || ordinal >= values().length) {
	                throw new IndexOutOfBoundsException("Invalid ordinal");
	            }
	            return values()[ordinal];
	        }
		}
    
    /**
     * 商品
     * @param selectRecommends
     * @return
     */
    public List<SelectRecommend> getSelectRecommendFromString(String selectRecommends) {
    	List<SelectRecommend> selectRecommendList = new ArrayList<>();
        if(StringUtils.isBlank(selectRecommends)) {
            return selectRecommendList;
        }
        String[] strArr = selectRecommends.split(",");
        for(String str : strArr) {
            try {
                int selectIndex = Integer.parseInt(str);
                selectRecommendList.add(SelectRecommend.valueOf(selectIndex));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return selectRecommendList;
    }
    

    public String getStringFromSelectList(List<SelectRecommend> selectRecommendList) {
        if(null == selectRecommendList || selectRecommendList.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<selectRecommendList.size(); i++) {

            sb.append(selectRecommendList.get(i).ordinal());
            if(i==selectRecommendList.size()-1) {
                break;
            }
            sb.append(",");
        }
        return sb.toString();
    }
    
    /**
     * USER
     * @param selectRecommends
     * @return
     */
    public List<UserRecommend> getUserRecommendFromString(String userRecommend) {
    	List<UserRecommend> userRecommendList = new ArrayList<>();
        if(StringUtils.isBlank(userRecommend)) {
            return userRecommendList;
        }
        String[] strArr = userRecommend.split(",");
        for(String str : strArr) {
            try {
                int selectIndex = Integer.parseInt(str);
                userRecommendList.add(UserRecommend.valueOf(selectIndex));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return userRecommendList;
    }

    public String getStringFromUserSelectList(List<UserRecommend> userRecommendList) {
        if(null == userRecommendList || userRecommendList.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<userRecommendList.size(); i++) {

            sb.append(userRecommendList.get(i).ordinal());
            if(i==userRecommendList.size()-1) {
                break;
            }
            sb.append(",");
        }
        return sb.toString();
    }
    
    /**
     * GAME
     * @param selectRecommends
     * @return
     */
    public List<GameRecommend> getGameRecommendFromString(String gameRecommend) {
    	List<GameRecommend> gameRecommendList = new ArrayList<>();
        if(StringUtils.isBlank(gameRecommend)) {
            return gameRecommendList;
        }
        String[] strArr = gameRecommend.split(",");
        for(String str : strArr) {
            try {
                int selectIndex = Integer.parseInt(str);
                gameRecommendList.add(GameRecommend.valueOf(selectIndex));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return gameRecommendList;
    }

    public String getStringFromGameselectList(List<GameRecommend> gameRecommendList) {
        if(null == gameRecommendList || gameRecommendList.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<gameRecommendList.size(); i++) {

            sb.append(gameRecommendList.get(i).ordinal());
            if(i==gameRecommendList.size()-1) {
                break;
            }
            sb.append(",");
        }
        return sb.toString();
    }
    
    /**
     * SAFE
     * @param selectRecommends
     * @return
     */
    public List<SafeRecommend> getSafeRecommendFromString(String safeRecommend) {
    	List<SafeRecommend> safeRecommendList = new ArrayList<>();
        if(StringUtils.isBlank(safeRecommend)) {
            return safeRecommendList;
        }
        String[] strArr = safeRecommend.split(",");
        for(String str : strArr) {
            try {
                int selectIndex = Integer.parseInt(str);
                safeRecommendList.add(SafeRecommend.valueOf(selectIndex));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return safeRecommendList;
    }

    public String getStringFromSafeselectList(List<SafeRecommend> safeRecommendList) {
        if(null == safeRecommendList || safeRecommendList.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<safeRecommendList.size(); i++) {

            sb.append(safeRecommendList.get(i).ordinal());
            if(i==safeRecommendList.size()-1) {
                break;
            }
            sb.append(",");
        }
        return sb.toString();
    }
    
    

    /**
     * MONEY
     * @param selectRecommends
     * @return
     */
    public List<MoneyRecommend> getMoneyRecommendFromString(String moneyRecommend) {
    	List<MoneyRecommend> moneyRecommendList = new ArrayList<>();
        if(StringUtils.isBlank(moneyRecommend)) {
            return moneyRecommendList;
        }
        String[] strArr = moneyRecommend.split(",");
        for(String str : strArr) {
            try {
                int selectIndex = Integer.parseInt(str);
                moneyRecommendList.add(MoneyRecommend.valueOf(selectIndex));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return moneyRecommendList;
    }

    public String getStringFromMoneyselectList(List<MoneyRecommend> moneyRecommendList) {
        if(null == moneyRecommendList || moneyRecommendList.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<moneyRecommendList.size(); i++) {

            sb.append(moneyRecommendList.get(i).ordinal());
            if(i==moneyRecommendList.size()-1) {
                break;
            }
            sb.append(",");
        }
        return sb.toString();
    }
    
    
    

    
    /**
	 * 将controller拼装的domain转化为需要保存到数据库的domain,主要步骤为
	 * 1、在库中查出相同id的domain
	 * 2、遍历allowed filed，将自身允许修改的属性传给库中的domain
	 * 3、将库中的domain属性回传给自身
	 * 
	 * 本方法主要用于防止手动构建form的攻击，并解决createddate等隐藏参数，在页面保存后为空的情况
	 * @param fields controller中定义的allowed filed，使用@InitBinder定义。
	 */
	@SuppressWarnings("unchecked")
	public void merge(String[] fields){
		if(!this.isNew()){
			 
			//List<SelectRecommend> list = this.getSelectRecommendList();
			List<SelectRecommend> selectRecommendList = this.getSelectRecommendList();
		    List<UserRecommend> userRecommendList = this.getUserRecommendList();
		    List<GameRecommend> gameRecommendList = this.getGameRecommendList();
		    List<SafeRecommend> safeRecommendList = this.getSafeRecommendList();
		    List<MoneyRecommend> moneyRecommendList = this.getMoneyRecommendList();
			
			Object thisDomainInDB = null;
			try {
                thisDomainInDB = BeanUtils.cloneBean(((JpaRepository) getRepository()).findOne(this.getId()));
			} catch (IllegalAccessException | InstantiationException
					| InvocationTargetException | NoSuchMethodException e1) {
				logger.debug("error in copy merge a domain",e1);
			}			
			for(String field : fields){
				try {
                    String property = BeanUtils.getProperty(this,field);
                    if(field.endsWith("Date")) {
                        Date date = new SimpleDateFormat("EE MMM dd HH:mm:ss 'CST' yyyy", java.util.Locale.US).parse(property);
                        BeanUtils.copyProperty(thisDomainInDB, field, date);
                    }else {
                        BeanUtils.copyProperty(thisDomainInDB, field, property);
                    }
				} catch (IllegalAccessException | InvocationTargetException
						| NoSuchMethodException e) {
					logger.debug("error in copy merge a domain",e);
				} catch (ParseException e) {
                    e.printStackTrace();
                }
            }
			try {
				BeanUtils.copyProperties(this, thisDomainInDB);
				this.setSelectRecommendList(selectRecommendList);
				this.setUserRecommendList(userRecommendList);
				this.setGameRecommendList(gameRecommendList);
				this.setSafeRecommendList(safeRecommendList);
				this.setMoneyRecommendList(moneyRecommendList);
			} catch (IllegalAccessException | InvocationTargetException e) {
				logger.debug("error in copy merge a domain",e);
			}
		}
	}
	
	
}
